import createjs from 'createjs-ts';
import { CRUMB_MAX_NUM, PLAYGROUND_WIDTH, PLAYGROUND_HEIGHT, MAX_PROP_NUM} from './Setting';
import Util from './Util';
import MapManager from './MapManager';
const CRUMB_UPDATE_INTERVAL = 500;
const getRandomColor = Util.getRandomColor;
import Crumb from './Crumb'

let crumbs = new Map();
let _crumbUpdateDelta = 0;

let propMaps = new Map();
/**
 * 食物管理
 */
class CrumbManager{
	constructor(){
		this.renderMap = null // 渲染在哪张地图
	}
	init(renderMap){
		// 设置渲染地图
		this.renderMap = renderMap;
		for(let i = 0; i < CRUMB_MAX_NUM; i++){
			this.addCrumb({});
		}
	}
	/**
	 * 增加食物
	 * @param {} param0 
	 */
	addCrumb({x, y, r, color, score, type}){
		let foodEntity = new Crumb(color || getRandomColor(), r, type);
		foodEntity.x = x !== undefined ? x : Math.round(Math.random()*(PLAYGROUND_WIDTH-20)) + 10;
		foodEntity.y = y !== undefined ? y : Math.round(Math.random()*(PLAYGROUND_HEIGHT-20)) + 10;
		foodEntity.score = score || 3; //默认分数
		if(type) foodEntity.type = type;

		this.renderMap.addChild(foodEntity); // 地图上添加食物
		crumbs.set(foodEntity.id, foodEntity);
		MapManager.AddToABlock(foodEntity);
	}

	deleteCrumb(entity, pos){
		createjs.Tween.get(entity).to({x:pos.x, y: pos.y}, 100).call(()=>{
			MapManager.RemoveFromABlock(entity);
			this.renderMap && this.renderMap.removeChild(entity);
			crumbs.delete(entity.id);
		});
		//entity.uncache();
	}

	update(dt){
		_crumbUpdateDelta += dt;
		if(_crumbUpdateDelta > CRUMB_UPDATE_INTERVAL){
			_crumbUpdateDelta -= CRUMB_UPDATE_INTERVAL;
			let needFoodNum = CRUMB_MAX_NUM - crumbs.size;
			for(; needFoodNum>=0; needFoodNum--){
				// 增加食物
				this.addCrumb({});
			}
			// 添加道具
			this.updateProp({})
		}
	}
	updateProp({x, y, r, color, score, type}){
		if(propMaps.size > 2) return // 道具最多只能有两个
		let foodEntity = new Crumb('#f00', 60, 'PROP');
		foodEntity.x = x !== undefined ? x : Math.round(Math.random()*(PLAYGROUND_WIDTH-60)) + 10;
		foodEntity.y = y !== undefined ? y : Math.round(Math.random()*(PLAYGROUND_HEIGHT-60)) + 10;
		foodEntity.score = 0;
		foodEntity.propType = 'invincible';
		this.renderMap.addChild(foodEntity); // 地图上添加食物
		propMaps.set(foodEntity.id, foodEntity);
		MapManager.AddToABlock(foodEntity);
	}
	deleteProp(entity, pos){
		createjs.Tween.get(entity).to({x:pos.x, y: pos.y}, 100).call(()=>{
			MapManager.RemoveFromABlock(entity);
			this.renderMap && this.renderMap.removeChild(entity);
			propMaps.get(entity.id)?.clearPropInterVal()
			propMaps.delete(entity.id);
		});
		//entity.uncache();
	}
	clear(){
		crumbs = new Map();
		this.renderMap = null;
		_crumbUpdateDelta = 0;
	}
}

export default new CrumbManager();